//
//  LoginViewController.m
//  misDesesos
//
//  Created by Roger Plana Casadella on 11/11/11.
//  Copyright (c) 2011 Champions Freak. All rights reserved.
//

#import "LoginViewController.h"
#import "MainViewController.h"
#import "SOTextField.h"

@implementation LoginViewController

@synthesize loginTF;
@synthesize passTF;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) 
    {
        // Custom initialization
    }
    return self;
}

#pragma mark - Actions

- (BOOL) textFieldShouldReturn:(UITextField *) textField {
    
    BOOL didResign = [textField resignFirstResponder];
    if (!didResign) return NO;
    
    if ([textField isKindOfClass:[SOTextField class]])
    {
        SOTextField *tf = (SOTextField *)textField;
        if (tf.nextField != nil)
        {
            dispatch_async(dispatch_get_current_queue(), 
                           ^ { [[(SOTextField *)textField nextField] becomeFirstResponder]; });
        }
        else [self login];
        
    }
    
    return YES;
    
}

- (IBAction) textFieldDoneEditing : (id) sender
{
    [sender resignFirstResponder];
}
- (IBAction) backgroundTap:(id) sender
{
    [loginTF resignFirstResponder];
    [passTF resignFirstResponder];
}

#pragma mark - Private Methods

-(void)processResponse:(NSString *)response
{
    //Treiem el monitor d'activitat
    [DSBezelActivityView removeViewAnimated:NO];
    
    NSMutableDictionary *loginData = [response JSONValue];
    NSString *responseCode = [loginData objectForKey:@"type"];
    if ([responseCode isEqualToString:@"response"])
    {
        NSString *stat = [loginData objectForKey:@"stat"];
        if ([stat isEqualToString:@"OK"])
        {
            NSMutableDictionary *respData = [loginData objectForKey:@"data"];
            for (NSDictionary *dic in respData)
            {
                [mvc setUserName:[dic objectForKey:@"name"]];
                [mvc setHashID:[dic objectForKey:@"hash"]];
            }
            [mvc LoadDashboard:self];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                            message:@"El nombre de usuario i password no son correctos"
                                                           delegate:self 
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            
            [alert show];
            [alert release];
        }
    }
    else
    {
        NSString *errorStr = [loginData objectForKey:@"msn"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR"
                                                        message:errorStr
                                                       delegate:self 
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        
        [alert show];
        [alert release];
    }
}

-(void)login
{
    //comprobem que el camp de login està omplert
    if ( ![[loginTF text] length] > 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR"
                                                        message:@"Login can't be empty"
                                                       delegate:self 
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return;
    }
    
    //Comprobem si el camp de password està ple
    if ( ![[passTF text] length] > 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR"
                                                        message:@"Password can't be empty"
                                                       delegate:self 
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return;
    }
    [self loginRequest];
}

-(void)loginRequest
{
    //Posem un notificador d'activitat
    [DSBezelActivityView newActivityViewForView:self.view withLabel:@"Logging in..."];
    
    //Hem de fer la petició amb les dades que hi han al formulari
    NSURL *url = [NSURL URLWithString:BASE_URL];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSString *args = [NSString stringWithFormat:@"%@,%@",[loginTF text],[passTF text]];
    [request setPostValue:args forKey:@"a"];
    [request setDelegate:self];
    [request startAsynchronous];
}

#pragma mark - ASIHTTPRequest Delegate Methods

- (void)requestFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    [self processResponse:[request responseString]];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    [DSBezelActivityView removeViewAnimated:YES];
    if ([error code] == 2)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR"
                                                        message:@"The request timed out, try again later"
                                                       delegate:self 
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        
        [alert show];
        [alert release];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR"
                                                        message:@"There has been an error with the server, pleas try again later"
                                                       delegate:self 
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        
        [alert show];
        [alert release]; 
    }
    NSLog(@"ERROR --> %@",[error localizedDescription]);
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    mvc = [MainViewController sharedMainViewController];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [super dealloc];
}

@end
